import os
import csv


def clear_screen():
    # 清屏函数，根据操作系统进行清屏
    os.system('cls' if os.name == 'nt' else 'clear')


def menu():
    # 菜单函数，显示菜单选项
    print("BMR 计算器")
    print("1. 计算 BMR")
    print("2. 导出表格")
    print("3. 清除历史记录")
    print("4. 退出")


def count():
    # 计算身高函数
    while True:
        height_input = input("请输入您的身高（厘米或英尺/英寸）：")
        try:
            if "cm" in height_input:
                height = float(height_input.replace("cm", ""))
                return height
            elif "'" in height_input and '"' in height_input:
                feet, inches = height_input.split("'")
                feet = float(feet)
                inches = float(inches.replace('"', ''))
                height = feet * 30.48 + inches * 2.54
                return height
            else:
                raise ValueError
        except ValueError:
            print("无效的身高输入，请重新输入。")


def validate_weight_input():
    # 验证体重输入函数
    while True:
        weight_input = input("请输入您的体重（千克）：")
        try:
            weight = float(weight_input)
            return weight
        except ValueError:
            print("无效的体重输入，请重新输入。")


def calculate_bmr(gender, age, height, weight):
    # 计算 BMR 函数
    if gender == "男":
        bmr = 10 * weight + 6.25 * height - 5 * age + 5
    elif gender == "女":
        bmr = 10 * weight + 6.25 * height - 5 * age - 161
    else:
        print("无效的性别输入。")
        return None
    return bmr



def save_bmr_data_as_csv(data):
    file_exists = os.path.isfile('bmr data.csv')
    with open('bmr data.csv', 'a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)

        if not file_exists:
            writer.writerow(['性别', '年龄', '身高', '体重', 'BMR'])

        for row in data:
            writer.writerow(row)



def load_bmr_data_from_csv():
    data = []
    if os.path.isfile('bmr data.csv'):
        with open('bmr data.csv', 'r', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            next(reader, None)  # 跳过标题行
            for row in reader:
                data.append(row)
    return data


def clear_bmr_data():
    if os.path.isfile('bmr data.csv'):
        os.remove('bmr data.csv')
        print("历史数据已清除。")
    else:
        print("没有历史数据。")


def export_bmr_data_as_csv():
    data = load_bmr_data_from_csv()

    if len(data) == 0:
        print("没有保存的数据。")
    else:
        filename = "bmr data.csv"
        with open(filename, 'w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(['性别', '年龄', '身高', '体重', 'BMR'])
            for row in data:
                writer.writerow([row['性别'], row['年龄'], row['身高'], row['体重'], row['BMR']])

        print(f"数据已成功导出为CSV文件：{filename}")

def main():
    data = load_bmr_data_from_csv()

    while True:
        clear_screen()
        menu()
        choice = input("请输入选项（1/2/3/4）：")

        if choice == "1":
            clear_screen()

            while True:
                gender = input("请输入您的性别（男/女）：")
                if gender == "男" or gender == "女":
                    break
                else:
                    print("无效的性别输入，请重新输入。")

            age = int(input("请输入您的年龄："))
            height = count()
            weight = validate_weight_input()
            bmr = calculate_bmr(gender, age, height, weight)

            print("您的基础代谢率（BMR）是：", bmr)

            save_data = input("是否保存数据？（是/否）：")
            if save_data == "是":
                data.append([gender, age, height, weight, bmr])
                save_bmr_data_as_csv(data)
                print("数据保存成功！")

            input("按 Enter 键返回菜单。")

        elif choice == "2":
            export_bmr_data_as_csv()

        elif choice == "3":
            clear_screen()
            clear_bmr_data()
            input("按 Enter 键返回菜单。")

        elif choice == "4":
            print("谢谢使用！再见！")
            break

        else:
            print("无效的选项，请重新输入。")
            input("按 Enter 键返回菜单。")


if __name__ == '__main__':
    main()